package com.example.spring_xx_u_market;

import com.example.bean.ErrorCodeV;
import com.example.bean.LoginV;
import com.example.bean.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import util.UtilTime;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.example.spring_xx_u_market.SpringXxUMarketApplication.jdbcTemplate;

@Slf4j
@RestController
@RequestMapping("api")
public class LoginVCtrl {
    @PostMapping("login")
    public Object getLogin(HttpServletRequest request) {
        int account;
        String accountStr = request.getParameter("account");
        String password = request.getParameter("password");
        if (accountStr == null || password == null) {
            return new ErrorCodeV("005");
        } else {
            account = Integer.parseInt(accountStr);
        }

        List<UserInfo> query = jdbcTemplate.query("select * from second_hand.user_info where account=? and password=?",
                new BeanPropertyRowMapper<>(UserInfo.class), account, password);
        if (query.size() == 1) {
            jdbcTemplate.update("update second_hand.user_info set last_login_time =? where account= ?", UtilTime.getStringTimeNow(), account);
            return new LoginV(query.get(0));
        } else {
            return new ErrorCodeV("001");//001 - 账号或密码不正确
        }
    }
}
